<template>
  <div class="initiated">
    <div class="page-container">
      <div class="page-header">
        <h2>我发起的</h2>
        <el-button type="primary" @click="goToApply">
          <el-icon><Plus /></el-icon>
          新建申请
        </el-button>
      </div>
      
      <!-- 筛选条件 -->
      <el-card class="filter-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="申请状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="待审批" value="pending" />
              <el-option label="审批中" value="approving" />
              <el-option label="已批准" value="approved" />
              <el-option label="已驳回" value="rejected" />
              <el-option label="执行中" value="executing" />
              <el-option label="已关闭" value="closed" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="作业类型">
            <el-select v-model="searchForm.workType" placeholder="全部类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="高空作业" value="high_altitude" />
              <el-option label="动火作业" value="hot_work" />
              <el-option label="电气作业" value="electrical" />
              <el-option label="受限空间" value="confined_space" />
              <el-option label="起重作业" value="lifting" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 申请列表 -->
      <el-card>
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
        >
          <el-table-column prop="permitNumber" label="许可证编号" width="150" />
          <el-table-column prop="workType" label="作业类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getWorkTypeTagType(row.workType)">
                {{ getWorkTypeLabel(row.workType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="作业地点" width="200" />
          <el-table-column prop="department" label="作业部门" width="120" />
          <el-table-column prop="startTime" label="开始时间" width="160" />
          <el-table-column prop="endTime" label="结束时间" width="160" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="currentApprover" label="当前审批人" width="120" />
          <el-table-column prop="createTime" label="申请时间" width="160" />
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)">
                查看
              </el-button>
              <el-button 
                v-if="canEdit(row.status)" 
                type="warning" 
                size="small" 
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button 
                v-if="canCancel(row.status)" 
                type="danger" 
                size="small" 
                @click="handleCancel(row)"
              >
                撤销
              </el-button>
              <el-button 
                v-if="canExtend(row.status)" 
                type="info" 
                size="small" 
                @click="handleExtend(row)"
              >
                延期
              </el-button>
              <el-button 
                v-if="canClose(row.status)" 
                type="success" 
                size="small" 
                @click="handleClose(row)"
              >
                关闭
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

interface InitiatedItem {
  id: number
  permitNumber: string
  workType: string
  location: string
  department: string
  startTime: string
  endTime: string
  status: string
  currentApprover: string
  createTime: string
}

const loading = ref(false)
const tableData = ref<InitiatedItem[]>([])

const searchForm = reactive({
  status: '',
  workType: '',
  dateRange: []
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 模拟数据
const mockData: InitiatedItem[] = [
  {
    id: 1,
    permitNumber: 'WP20250115001',
    workType: 'high_altitude',
    location: 'A区3楼外墙维修',
    department: '维修部',
    startTime: '2025-01-16 08:00',
    endTime: '2025-01-16 17:00',
    status: 'approving',
    currentApprover: '李安全',
    createTime: '2025-01-15 14:30'
  },
  {
    id: 2,
    permitNumber: 'WP20250115002',
    workType: 'hot_work',
    location: 'B区管道焊接',
    department: '维修部',
    startTime: '2025-01-17 09:00',
    endTime: '2025-01-17 15:00',
    status: 'approved',
    currentApprover: '-',
    createTime: '2025-01-15 10:20'
  },
  {
    id: 3,
    permitNumber: 'WP20250115003',
    workType: 'electrical',
    location: '配电室设备检修',
    department: '维修部',
    startTime: '2025-01-18 08:30',
    endTime: '2025-01-18 16:30',
    status: 'executing',
    currentApprover: '-',
    createTime: '2025-01-15 09:15'
  },
  {
    id: 4,
    permitNumber: 'WP20250115004',
    workType: 'confined_space',
    location: '储罐内部清洗',
    department: '生产部',
    startTime: '2025-01-19 10:00',
    endTime: '2025-01-19 18:00',
    status: 'rejected',
    currentApprover: '-',
    createTime: '2025-01-15 16:45'
  },
  {
    id: 5,
    permitNumber: 'WP20250115005',
    workType: 'lifting',
    location: 'C区设备吊装',
    department: '维修部',
    startTime: '2025-01-20 08:00',
    endTime: '2025-01-20 12:00',
    status: 'closed',
    currentApprover: '-',
    createTime: '2025-01-15 11:30'
  }
]

// 获取申请列表
const fetchInitiated = async () => {
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    let filteredData = mockData
    
    // 根据筛选条件过滤
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    if (searchForm.workType) {
      filteredData = filteredData.filter(item => item.workType === searchForm.workType)
    }
    
    // 分页
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    
    tableData.value = filteredData.slice(start, end)
    pagination.total = filteredData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取申请列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchInitiated()
}

// 重置
const handleReset = () => {
  searchForm.status = ''
  searchForm.workType = ''
  searchForm.dateRange = []
  pagination.page = 1
  fetchInitiated()
}

// 查看详情
const handleView = (row: InitiatedItem) => {
  router.push(`/permit/detail/${row.id}`)
}

// 编辑申请
const handleEdit = (row: InitiatedItem) => {
  router.push(`/permit/edit/${row.id}`)
}

// 撤销申请
const handleCancel = async (row: InitiatedItem) => {
  try {
    await ElMessageBox.confirm(`确定要撤销许可证 "${row.permitNumber}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('撤销成功')
    fetchInitiated()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '撤销失败')
    }
  }
}

// 延期申请
const handleExtend = (row: InitiatedItem) => {
  ElMessage.info('延期申请功能开发中...')
}

// 关闭申请
const handleClose = async (row: InitiatedItem) => {
  try {
    await ElMessageBox.confirm(`确定要关闭许可证 "${row.permitNumber}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('关闭成功')
    fetchInitiated()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '关闭失败')
    }
  }
}

// 跳转到申请页面
const goToApply = () => {
  router.push('/permit/apply')
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchInitiated()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchInitiated()
}

// 获取作业类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    high_altitude: 'warning',
    hot_work: 'danger',
    electrical: 'primary',
    confined_space: 'info',
    lifting: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取作业类型标签
const getWorkTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    high_altitude: '高空作业',
    hot_work: '动火作业',
    electrical: '电气作业',
    confined_space: '受限空间',
    lifting: '起重作业'
  }
  return labelMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'info',
    approving: 'warning',
    approved: 'success',
    rejected: 'danger',
    executing: 'primary',
    closed: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    pending: '待审批',
    approving: '审批中',
    approved: '已批准',
    rejected: '已驳回',
    executing: '执行中',
    closed: '已关闭'
  }
  return labelMap[status] || status
}

// 判断是否可以编辑
const canEdit = (status: string) => {
  return ['pending', 'rejected'].includes(status)
}

// 判断是否可以撤销
const canCancel = (status: string) => {
  return ['pending', 'approving'].includes(status)
}

// 判断是否可以延期
const canExtend = (status: string) => {
  return ['approved', 'executing'].includes(status)
}

// 判断是否可以关闭
const canClose = (status: string) => {
  return ['approved', 'executing'].includes(status)
}

onMounted(() => {
  fetchInitiated()
})
</script>

<style lang="scss" scoped>
.initiated {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

